package info.cs52.xdao;

import info.cs52.fes.lp.PhrasePattern;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PhrasePatternXDAO {
	public static List<PhrasePattern> fetchAnswerPatterns() {
		LinkedList<PhrasePattern> result = new LinkedList<PhrasePattern>();
		try {

			File fXmlFile = new File("patterns/AnswerPatterns.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();

			System.out.println("Root element :"
					+ doc.getDocumentElement().getNodeName());
			NodeList ppnList = doc.getElementsByTagName("phrasepattern");
			System.out.println("-----------------------");

			
			
			for (int iPP = 0; iPP < ppnList.getLength(); iPP++) {

				Node ppnNode = ppnList.item(iPP);
				if (ppnNode.getNodeType() == Node.ELEMENT_NODE) {
					
					PhrasePattern tempPP = new PhrasePattern();
					
					Element ppeElement = (Element) ppnNode;
					
					String pattern = getTagValue("pattern", ppeElement);
					tempPP.setPattern(pattern);
					System.out.println("Pattern : "
							+ pattern);
					
					NodeList spnList = ppeElement.getElementsByTagName("simplePhrases");
					System.out.println("Simple Phrases: ");
					
					String[] simplePhrases = new String[spnList.getLength()];
					
					for (int iSP = 0; iSP < spnList.getLength(); iSP++) {

						Node spnNode = spnList.item(iSP);
						if (spnNode.getNodeType() == Node.ELEMENT_NODE) {

							Element speElement = (Element) spnNode;
							String eSimple = getTagValue("eSimple", speElement);
							simplePhrases[iSP] = eSimple;
							System.out.println("\teSimple : "
									+ eSimple);
						}
					}
					tempPP.setSimplePhrases(simplePhrases);
					
					String type = getTagValue("type", ppeElement);
					tempPP.setType(Integer.parseInt(type));
					System.out.println("Type : "
							+ type);
					
					result.add(tempPP);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private static String getTagValue(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
				.getChildNodes();

		Node nValue = (Node) nlList.item(0);
		return nValue.getNodeValue();
	}
}
